package com.shqcjd.yunweiyanoperator.ui.activity;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.CollectionBean;
import com.shqcjd.yunweiyanoperator.model.pojo.ShareVideoBean;
import com.shqcjd.yunweiyanoperator.ui.adapter.CollectionAdapter;
import com.shqcjd.yunweiyanoperator.ui.adapter.CollectionVideoListAdapter;
import com.shqcjd.yunweiyanoperator.ui.adapter.SquareVideoListAdapter;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.Config;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.SpacesItemDecoration;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.WrapContentLinearLayoutManager;
import com.shqcjd.yunweiyanoperator.widget.AddTipDialog;
import com.shuyu.gsyvideoplayer.GSYVideoManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 收藏页面
 */
public class CollectionActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener {
    List<CollectionBean.ListBean> mList = new ArrayList<>();
    @BindView(R.id.rv_collection)
    RecyclerView rvCollection;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    private Context mContext;
    private static final int PAGE_SIZE = Config.PAGE_TOTAL;
    private int mNextRequestPage = 1;
    private View notDataView;
    private CollectionVideoListAdapter collectionVideoListAdapter;
    private AddTipDialog addTipDialog;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_collection;
    }

    @Override
    public void init() {
        super.init();
        mContext = this;
    }

    @Override
    public void initView() {
        super.initView();
        tvTitle.setText("我的收藏");

        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) rvCollection.getParent(), false);
        initRefreshLayout();
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        rvCollection.setLayoutManager(staggeredGridLayoutManager);
        collectionVideoListAdapter = new CollectionVideoListAdapter();
        rvCollection.setAdapter(collectionVideoListAdapter);
        rvCollection.addItemDecoration(new SpacesItemDecoration(16, 16));
        collectionVideoListAdapter.setOnLoadMoreListener(this, rvCollection);
        collectionVideoListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CollectionBean.ListBean mBean = (CollectionBean.ListBean) adapter.getData().get(position);
                if (view.getId() == R.id.fl_delete || view.getId() == R.id.fl_sc) {
                    if (addTipDialog == null) {
                        addTipDialog = new AddTipDialog(mContext);
                    }
                    addTipDialog.setOnClickDialogListener(new AddTipDialog.setOnClickDialogListener() {
                        @Override
                        public void onClickAdd() {
                            cancelCollectionHttp(mBean.id + "", position);
                        }
                    });
                    addTipDialog.show();
                    addTipDialog.setStr("取消收藏", "是否要取消这一条收藏", "确认取消");
                } else if (view.getId() == R.id.btn_details) {
                    Intent intent = new Intent(mContext, VideoDetailsActivity.class);
                    intent.putExtra("title", mBean.title);
                    intent.putExtra("url", mBean.videoUrl);
                    intent.putExtra("imageUrl", mBean.imageUrl);
                    intent.putExtra("videoCategoryName", mBean.videoCategoryName);
                    intent.putExtra("userName", mBean.userName);
//                    intent.putExtra("callRecord", mBean.callRecord);
                    startActivity(intent);
                }

            }
        });
    }

    private void initRefreshLayout() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        swipeLayout.setRefreshing(true);
    }

    @Override
    public void initData() {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }

    private void refresh() {
        GSYVideoManager.releaseAllVideos();
        mNextRequestPage = 1;
        collectionVideoListAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        Map<String, Integer> map = new HashMap<>();
        map.put("page", mNextRequestPage);
        map.put("size", PAGE_SIZE);
        ApiService.collectionList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<CollectionBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        swipeLayout.setRefreshing(true);
                    }

                    @Override
                    public void _onNext(ResponseData<CollectionBean> retData) {
                        if (retData.retCode == 10000) {
                            setData(true, retData.data.list, collectionVideoListAdapter);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        collectionVideoListAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        collectionVideoListAdapter.setEnableLoadMore(true);
                        swipeLayout.setRefreshing(false);
                    }
                });
    }

    private void loadMore() {
        GSYVideoManager.releaseAllVideos();
        Map<String, String> map = new HashMap<>();
        map.put("page", mNextRequestPage + "");
        map.put("size", PAGE_SIZE + "");
        ApiService.collectionList(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<CollectionBean>>() {
                    @Override
                    public void _onNext(ResponseData<CollectionBean> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            boolean isRefresh = mNextRequestPage == 1;
                            setData(isRefresh, retData.data.list, collectionVideoListAdapter);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        collectionVideoListAdapter.loadMoreFail();
                    }
                });
    }

    private void cancelCollectionHttp(String collectId, int pos) {
        Map<String, String> map = new HashMap<>();
        map.put("collectId", collectId);
        ApiService.cancelCollection(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "取消成功");
                            collectionVideoListAdapter.remove(pos);
                            if (collectionVideoListAdapter.getData().size() == 0) {
                                collectionVideoListAdapter.setEmptyView(notDataView);
                            }
                            if (addTipDialog != null) {
                                addTipDialog.dismiss();
                            }
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }
                });
    }

    private void setData(boolean isRefresh, List data, BaseQuickAdapter adapter) {

        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            if (size > 0) {
                adapter.setNewData(data);
            } else {
                adapter.setNewData(null);
                adapter.setEmptyView(notDataView);
            }
        } else {
            if (size > 0) {
                adapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            adapter.loadMoreEnd(isRefresh);
        } else {
            adapter.loadMoreComplete();
        }
    }


    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }


}
